﻿using System;

namespace ChinesePinYin
{
    using System.Reflection;
    using System.IO;
    using System.Collections.ObjectModel;
    public static class PinYinInitialLetter
    {
        static PinYinInitialLetter()
        {
            if (embedAssembly != null)
                return;
            Assembly thisAsm = Assembly.GetExecutingAssembly();
            string resounceFullName = string.Concat(thisAsm.FullName.Split(',')[0], ".", RESOURCENAME);
            using (BinaryReader reader = new BinaryReader(thisAsm.GetManifestResourceStream(resounceFullName)))
            {
                byte[] bytes = reader.ReadBytes((int)reader.BaseStream.Length);
                embedAssembly = Assembly.Load(bytes);
            }
            embedConvertType = embedAssembly.GetType(INSTANCE_FULLNAME);
        }

        static Assembly embedAssembly = null;
        static Type embedConvertType = null;

        const string RESOURCENAME = "ChnCharInfo.dll";
        const string INSTANCE_FULLNAME = "Microsoft.International.Converters.PinYinConverter.ChineseChar";


        public static string Read(string text)
        {
            string result = string.Empty;
            foreach (char obj in text)
            {
                try
                {
                    object instance = Activator.CreateInstance(embedConvertType, obj);
                    ReadOnlyCollection<string> member = (ReadOnlyCollection<string>)instance.GetType().GetProperty("Pinyins").GetValue(instance, null);

                    for (int i = member.Count - 1; i >= 0; i--)
                    {
                        if (member[i] != null)
                        {
                            result += member[i][0].ToString();
                            break;
                        }
                    }
                }
                catch
                {
                    System.Diagnostics.Debug.WriteLine(text);
                    //result += obj.ToString();
                }
            }
            return result;

        }
    }
}